package com.klm.easymq.demo.service;

import com.klm.easymq.annotation.MQProducer;
import com.klm.easymq.demo.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 订单服务类
 * 演示Easy-MQ SDK的消息生产者功能
 */
@Slf4j
@Service
public class OrderService {
    
    /**
     * 创建订单并发送消息
     * 使用@MQProducer注解自动发送消息到MQ
     */
    @MQProducer(
        topic = "order.created",
        tag = "create",
        key = "#order.orderId"
    )
    public Order createOrder(String userId, String productId, String productName, BigDecimal amount) {
        // 创建订单
        Order order = Order.builder()
                .orderId(generateOrderId())
                .userId(userId)
                .productId(productId)
                .productName(productName)
                .amount(amount)
                .status("CREATED")
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .remark("订单创建成功")
                .build();
        
        log.info("创建订单: {}", order);
        
        // 返回订单对象，@MQProducer会自动将其发送到MQ
        return order;
    }
    
    /**
     * 更新订单状态并发送消息
     */
    @MQProducer(
        topic = "order.updated",
        tag = "update",
        key = "#order.orderId"
    )
    public Order updateOrderStatus(String orderId, String status) {
        // 模拟更新订单状态
        Order order = Order.builder()
                .orderId(orderId)
                .status(status)
                .updateTime(LocalDateTime.now())
                .remark("订单状态更新为: " + status)
                .build();
        
        log.info("更新订单状态: orderId={}, status={}", orderId, status);
        
        return order;
    }
    
    /**
     * 取消订单并发送消息
     */
    @MQProducer(
        topic = "order.cancelled",
        tag = "cancel",
        key = "#order.orderId"
    )
    public Order cancelOrder(String orderId, String reason) {
        Order order = Order.builder()
                .orderId(orderId)
                .status("CANCELLED")
                .updateTime(LocalDateTime.now())
                .remark("订单取消原因: " + reason)
                .build();
        
        log.info("取消订单: orderId={}, reason={}", orderId, reason);
        
        return order;
    }
    
    /**
     * 生成订单ID
     */
    private String generateOrderId() {
        return "ORDER_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8);
    }
} 